package com.wjk.kylin.modules.system.role.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wjk.kylin.core.common.aspect.Log;
import com.wjk.kylin.core.common.controller.BaseController;
import com.wjk.kylin.core.common.data.RequestData;
import com.wjk.kylin.core.common.data.ResponseData;
import static com.wjk.kylin.core.constant.CommonConstant.BusinessType.*;

import com.wjk.kylin.core.common.valid.insert;
import com.wjk.kylin.core.common.valid.update;
import com.wjk.kylin.core.utils.PageUtils;
import com.wjk.kylin.modules.system.role.entity.Role;
import com.wjk.kylin.modules.system.role.service.IRoleService;
import com.wjk.kylin.modules.system.user.service.IUserRoleService;
import com.wjk.kylin.modules.system.vo.ListSelectVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangjkui
 * @since 2020-06-01
 */
@Api("角色")
@RestController
@RequestMapping("/sys/role")
public class RoleController extends BaseController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserRoleService userRoleService;

    @PreAuthorize("hasAuthority('system:role:list')")
    @ApiOperation("列表")
    @Log(title = "角色-列表",businessType = LIST,isSaveResponseData = false)
    @GetMapping("/list")
    public ResponseData list(Role role) {
        IPage<Role> page = roleService.findPage(new RequestData<Role>(),role);
        return ResponseData.success().data("page",new PageUtils(page));
    }

    @PreAuthorize("hasAuthority('system:role:query')")
    @ApiOperation("详情")
    @Log(title = "角色-详情",businessType = GET)
    @GetMapping("/{roleId}")
    public ResponseData get(@PathVariable String roleId) {
        Role role = roleService.getById(roleId);
        return ResponseData.success().data("role", role);
    }

    @PreAuthorize("hasAuthority('system:role:add')")
    @ApiOperation("新增")
    @Log(title = "角色-新增",businessType = INSERT)
    @PostMapping
    public ResponseData save(@Validated(insert.class) @RequestBody Role role) {
        boolean flag = roleService.save(role);
        if(flag){
            return ResponseData.success();
        }else {
            return ResponseData.error("新增失败");
        }
    }

    @PreAuthorize("hasAuthority('system:role:edit')")
    @ApiOperation("编辑")
    @Log(title = "角色-编辑",businessType = UPDATE)
    @PutMapping
    public ResponseData update(@Validated(update.class) @RequestBody Role role) {
        if(role.isAdmin()){
            return ResponseData.error("系统角色不能编辑");
        }
        boolean flag = roleService.update(role);
        if(flag){
            return ResponseData.success();
        }else {
            return ResponseData.error("编辑失败");
        }
    }

    @PreAuthorize("hasAuthority('system:role:delete')")
    @ApiOperation("删除")
    @Log(title = "角色-删除",businessType = DELETE)
    @DeleteMapping("/{roleIds}")
    public ResponseData delete(@PathVariable String[] roleIds) {
        if(ArrayUtils.contains(roleIds, 1)){
            return ResponseData.error("系统角色不能删除");
        }
        boolean flag = roleService.deleteByIds(roleIds);

        if(flag){
            return ResponseData.success();
        }else {
            return ResponseData.error("删除失败");
        }
    }

    @PreAuthorize("hasAuthority('system:role:edit')")
    @ApiOperation("数据权限")
    @Log(title = "角色-数据权限", businessType = UPDATE)
    @PutMapping("/dataScope")
    public ResponseData dataScope(@RequestBody Role role) {
        if(role.isAdmin()){
            return ResponseData.error("系统角色不能编辑");
        }
        boolean flag = roleService.authDataScope(role);

        if(flag){
            return ResponseData.success();
        }else {
            return ResponseData.error("编辑失败");
        }
    }

    @PreAuthorize("hasAuthority('system:role:edit')")
    @ApiOperation("状态修改")
    @Log(title = "角色-状态修改", businessType = UPDATE)
    @PatchMapping("/{roleId}/{status}")
    public ResponseData changeStatus(@PathVariable("roleId") String roleId,@PathVariable("status") String status) {
        if(StringUtils.equals("1",roleId)){
            return ResponseData.error("系统角色不能编辑");
        }

        boolean flag = roleService.changeStatus(roleId,status);
        if (flag) {
            return ResponseData.success();
        } else {
            return ResponseData.error("操作失败");
        }
    }


    @ApiOperation("角色下拉列表")
    @GetMapping("/select")
    public ResponseData select(){
        List<Role> roleList = roleService.list();

        List<ListSelectVO> list = roleList.stream().map(ListSelectVO::new).collect(Collectors.toList());

        return ResponseData.success().data("list",list);
    }

    @ApiOperation("加载对应用户角色")
    @GetMapping("/select/{userId}")
    public ResponseData roleUserIdSelect(@PathVariable("userId") String userId){
        List<Role> roleList = roleService.list();

        List<ListSelectVO> list = roleList.stream().map(ListSelectVO::new).collect(Collectors.toList());

        //用户拥有的角色id
        List<String> checkedKeys = userRoleService.findRoleListByUserId(userId);


        return ResponseData.success().data("list",list).data("checkedKeys",checkedKeys);
    }

}
